from collections import OrderedDict

from goods.models import GoodsChannel, GoodsCategory


def get_categories():
    """获取商品分类"""
    # 准备字典 有序字典
    categories = OrderedDict()
    # 查询并展示商品频道和分类
    # 查询频道
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        # 查询频道组
        group_id = channel.group_id
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}
        # 查询当前频道下的一级类别
        cat1 = channel.category
        categories[group_id]['channels'].append({'id': cat1.id, 'name': cat1.name, 'url': channel.url})
        # 查询当前一级类别下的二级类别
        sub_cats = GoodsCategory.objects.filter(parent_id=cat1.id)
        for sub_cat in sub_cats:
            categories[group_id]['sub_cats'].append({'id': sub_cat.id, 'name': sub_cat.name, 'sub_cats': []})
            # 查询当前二级类别下的三级类别
            sub_sub_cats = GoodsCategory.objects.filter(parent_id=sub_cat.id)
            for sub_sub_cat in sub_sub_cats:
                categories[group_id]['sub_cats'][-1]['sub_cats'].append(
                    {"id": sub_sub_cat.id, 'name': sub_sub_cat.name})
    return categories
